<template>
  <div
    class="container w-full h-full flex"
    v-if="currentQuestion && currentQuestion.answerScoreable"
  >
    <div class="left h-full bg-white flex-1 p-20px box-border overflow-hidden">
      <div ref="scroll" class="w-full h-full overflow-scroll">
        <Stem
          :data="stem"
          :answer="answer"
          :student-answer="studentAnswer"
          @change-student-answer="changeStudentAnswer"
          :readonly="studentAnswerStatus ? true : false"
        />
        <!-- answer -->
        <!-- <div v-show="isShowExplanation">
          <div class="module-item flex text-333 font-medium mt-20px mb-12px">
            <div class="rect mr-6px"></div>
            <div class="">答案</div>
          </div>
          <div
            class="answer p-20px bg-F4F7FB text-333"
            style="white-space: break-spaces; word-break: break-all"
            v-html="answerHtml"
          ></div>
        </div> -->
        <!-- explanation -->
        <div v-show="isShowExplanation">
          <div class="module-item flex text-333 font-medium mt-20px mb-12px">
            <div class="rect mr-6px"></div>
            <div class="">解析</div>
          </div>
          <div
            class="explanation p-20px bg-F4F7FB text-333"
            style="white-space: break-spaces; word-break: break-all"
            v-html="explanationHtml"
          ></div>
        </div>
      </div>
    </div>
    <div
      class="right h-full bg-white p-20px box-border ml-20px flex flex-col"
      style="font-size: 0.14rem"
    >
      <div class="flex-1"></div>
      <div class="footer px-20px box-border flex flex-col items-center">
        <div class="item-auto" v-show="studentAnswerStatus">
          <img
            v-show="isAddWqBook"
            src="@/assets/exercise/seed@2x.png"
            alt=""
            @click="onIsAddWqBookChange(false)"
            class="mr-6px"
          />
          <img
            v-show="!isAddWqBook"
            src="@/assets/exercise/crile@2x.png"
            alt=""
            class="mr-6px"
            @click="onIsAddWqBookChange(true)"
          />
          <span>将该题加入错题本</span>
        </div>
        <CustomButton
          class="block mt-20px"
          style="width: 2rem"
          @click="prevQuestion"
          v-show="isShowPrevBtn"
          >上一题
        </CustomButton>

        <CustomButton
          class="block mt-20px"
          style="width: 2rem"
          :style="
            hasMoreQuestion || questionIndex != questions.length - 1 ? '' : 'background:#DCDCDC'
          "
          @click="nextQuestion"
          v-show="isShowNextBtn"
          >下一题
        </CustomButton>
      </div>
    </div>
  </div>
</template>

<script>
import Stem from '@/components/question/exercise/stem/index'
import CustomButton from '@/components/button'
import { formatQuestionStem, formatQuestionAnswer } from '@/utils/question'
import { getListCompleteByIdsApi } from '@/api/exercise'

export default {
  components: {
    Stem,
    CustomButton
  },
  props: {
    questions: {
      type: Array,
      default: () => {
        return []
      }
    },
    questionIndex: {
      type: Number,
      default: 0
    },
    hasMoreQuestion: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      studentAnswerStatus: 0, // 0 => 未答题 1 => 已答题
      studentAnswer: '', // 学生作答答案
      isAddWqBook: false // 是否加入错题本
    }
  },
  computed: {
    currentQuestionIndex() {
      return this.questionIndex
    },
    currentQuestion() {
      return this.questions[this.questionIndex]
    },
    stem() {
      const {
        question: { stem },
        typeName
      } = this.currentQuestion

      const { type } = stem

      return formatQuestionStem(stem, {
        label: typeName,
        type
      })
    },
    answer() {
      const {
        question: { answer }
      } = this.currentQuestion

      return formatQuestionAnswer(answer)
    },
    answerHtml() {
      const { answer } = this.currentQuestion

      return answer
    },
    explanationHtml() {
      const { explanation } = this.currentQuestion

      if (!explanation)
        return '<div class="qml-explanation"><p class="paragraph" style=""><span>无</span></p></div>'

      return explanation.replace(/<p/g, '<p class="paragraph"')
    },
    // 是否显示解析
    isShowExplanation() {
      return this.studentAnswerStatus ? true : false
    },
    // 是否显示上一题按钮
    isShowPrevBtn() {
      return this.questionIndex != 0
    },
    // 是否显示下一题按钮
    isShowNextBtn() {
      return this.studentAnswerStatus ? true : false
    }
  },
  watch: {
    // 切换上一题/下一题，初始化答题状态/从缓存中读取答题状态
    questionIndex() {
      this.$refs.scroll && this.$refs.scroll.scrollTo(0, 0)
      const { temp } = this.currentQuestion

      if (!temp) {
        this.studentAnswerStatus = 0
        this.studentAnswer = ''
        this.isAddWqBook = false
      } else {
        this.studentAnswerStatus = temp['studentAnswerStatus']
        this.studentAnswer = temp['studentAnswer']
        this.isAddWqBook = temp['isAddWqBook']
      }
    }
  },
  methods: {
    // 更新当前题目（菁优网）
    updateCurrentQuestion() {
      return new Promise(async (resolve) => {
        const { questionId } = this.currentQuestion
        // 获取题目详情
        const loading = this.$loading({
          lock: true,
          text: '正在获取解析...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        })
        // 一分钟内上传不成功关闭loading弹窗
        const timer = setTimeout(() => {
          loading.close()
        }, 60000)
        const { data: questionSource, msg } = await getListCompleteByIdsApi({
          ids: questionId
        })
        clearTimeout(timer)
        loading.close()

        if (questionSource) {
          const { explanation, method, discuss } = questionSource[0]
          // 更新解析
          this.currentQuestion.explanation = `<div class=\"qml-explanation\" style=\"line-height: 0.28rem;\" data-copyright=\"jyeoo.com\"><div class=\"qml-seg\" seg-name=\"详解\">【分析】<div style=\"\">${explanation}</div></div><div class=\"qml-seg\" seg-name=\"解答\">【解答】<div style=\"\">${method}</div></div><div class=\"qml-seg\" seg-name=\"点评\">【点评】<div style=\"\">${discuss}</div></div></div>`
          this.currentQuestion.infoFlag = 1
        } else {
          this.$message.error(`获取题目解析失败，msg：${msg}`)
        }
        resolve()
      })
    },
    // 答题状态改变
    async changeStudentAnswer({ answer = {}, canNext = false }) {
      this.studentAnswer = answer

      if (canNext) {
        // 菁优网获取题目解析
        if (this.currentQuestion.sourceType === '3' && !this.currentQuestion.infoFlag) {
          await this.updateCurrentQuestion()
        }

        this.studentAnswerStatus = 1

        // 判断对错是否加入错题本
        if (
          answer &&
          String.prototype.localeCompare.call(
            JSON.stringify(answer),
            JSON.stringify(formatQuestionAnswer(this.answer))
          ) != 0
        ) {
          this.isAddWqBook = true // 加入错题本
        } else {
          this.isAddWqBook = false // 不加入错题本
        }

        this.submit() // 提交
      }
    },
    // 是否加入错题本状态改变
    onIsAddWqBookChange(value) {
      this.isAddWqBook = value

      // 未答题
      if (this.studentAnswerStatus === 0) {
        return
      }

      this.submit() // 提交
    },
    submit() {
      const {
        questionId,
        question: {
          stem: { type: questionType }
        },
        answerScoreable
      } = this.currentQuestion

      const data = {
        questionId, // 问题id
        questionSort: this.questionIndex + 1, // 题目序号
        questionType, // 题型
        answerScoreable, // 是否支持机阅
        questionAnswer: JSON.stringify(formatQuestionAnswer(this.answer)), // 题目答案
        studentAnswer: JSON.stringify(this.studentAnswer), // 学生作答答案
        studentAnswerUrl: '',
        correct:
          String.prototype.localeCompare.call(
            JSON.stringify(this.studentAnswer),
            JSON.stringify(formatQuestionAnswer(this.answer))
          ) == 0
            ? 0
            : 1, // 是否做对 0 对 1 错
        errors: this.isAddWqBook ? 0 : 1 // 是否加入错题本 0 加 1 不加
      }

      this.$emit('submit', data)

      // 缓存答题状态
      if (!this.currentQuestion.temp) {
        this.currentQuestion.temp = {
          studentAnswerStatus: this.studentAnswerStatus,
          studentAnswer: this.studentAnswer,
          isAddWqBook: this.isAddWqBook
        }
      }
    },
    prevQuestion() {
      this.$emit('prev')
    },
    nextQuestion() {
      // 没有下一题
      if (!this.hasMoreQuestion && this.questionIndex === this.questions.length - 1) {
        return
      }

      this.$emit('next')
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  .left {
    border-radius: 16px;

    .module-item {
      font-size: 26px;
      line-height: 26px;

      .rect {
        width: 4px;
        height: 26px;
        background: linear-gradient(180deg, #51c3ff 0%, #31b3f7 100%);
        border-radius: 3px;
      }
    }

    .answer,
    .explanation {
      font-size: 26px;
      line-height: 26px;
      border-radius: 8px;
    }
  }

  .right {
    border-radius: 16px;
    width: 303px;

    .footer {
      height: auto;
    }
    .item-auto {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 12px;
      flex-wrap: nowrap;
      img {
        width: 30px;
        height: 30px;
      }
      span {
        font-size: 26px;
        white-space: nowrap;
      }
    }
    .u-radio {
      font-size: 26px;
    }

    /deep/ .u-checkbox-label--left {
      span {
        font-size: 26px;
        color: #333;
      }

      .u-checkbox__icon-wrap--square span {
        color: #fff;
      }
    }
  }
}

/deep/ .el-checkbox {
  display: flex;
  align-items: center;
}

/deep/ .el-checkbox__label {
  font-size: 26px;
  color: #333;
}

/deep/ .el-checkbox__inner {
  width: 19px;
  height: 19px;
}

/deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
  color: #333;
}

/deep/ .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #51c3ff !important;
  border-color: #51c3ff;
}

/deep/ .el-checkbox__inner::after {
  left: 40%;
  top: 20%;
}

/deep/ .el-checkbox__input {
  height: 19px;
}
</style>
